package core.zb.tools;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
 * 拼音转换
 * @author Administrator
 *
 */
public class PinyinKit {
	public static String toPy(String content) {
		if (content == null || content.trim().length() == 0) {
			return "";
		}
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//音调的样式，默认 WITH_TONE_NUMBER

		StringBuilder pyBuilder = new StringBuilder();
		String temp;
		String[] pyArray = null;
		for (int i = 0; i < content.length(); i++) {
			char c = content.charAt(i);
			if ((int) c <= 128) {
				pyBuilder.append(c);
			} else {
				try {
					pyArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
				if (pyArray == null) {
					pyBuilder.append(c);
				} else {
					temp = pyArray[0];
					if (true) {
						temp = pyArray[0].toUpperCase().charAt(0) + temp.substring(1);
					}
					pyBuilder.append(temp).append(i == content.length() - 1 ? "" : "");
				}
			}
		}
		return pyBuilder.toString().trim();
	}
}
